package com.mallcai.bigdata.ladon.datasource;

import com.mallcai.bigdata.ladon.dpl.entity.common.Datasource;
import com.mallcai.bigdata.ladon.dpl.vo.DataType;
import com.mallcai.bigdata.ladon.vo.ColumnVo;
import com.mallcai.bigdata.ladon.vo.DataVo;
import com.mallcai.bigdata.ladon.vo.QueryParam;
import com.mallcai.bigdata.ladon.vo.TableVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by oneape<oneape15@163.com>
 * Created 2019-06-04 22:16.
 * Modify:
 */
@Slf4j
public class ElasticsearchHandler extends AbstractJdbcHandler {

    /**
     * 获取数据源下的所有表信息
     *
     * @param ds Datasource
     * @return List
     */
    @Override
    public List<TableVo> getAllTables(Datasource ds) {
        List<TableVo> tables = new ArrayList<>();

        QueryParam params = new QueryParam();
        params.setNeedLimit(false);
        params.setRawSql("SHOW TABLES");
        DataVo dataVo = executeSql(ds, params);

        if (dataVo == null || dataVo.getRowSize() == 0) {
            return tables;
        }

        for (Map<String, Object> row : dataVo.getRows()) {
            String name = String.valueOf(row.get("name"));
            if (StringUtils.startsWith(name, ".")) {
                continue;
            }

            String type = String.valueOf(row.get("type"));

            TableVo vo = new TableVo();
            vo.setName(name);
            vo.setDesc(type);
            tables.add(vo);
        }

        return tables;
    }

    /**
     * 获取表下面的所有字段信息
     *
     * @param ds        Datasource
     * @param tableName String
     * @return List
     */
    @Override
    public List<ColumnVo> getColumns(Datasource ds, String tableName) {
        List<ColumnVo> columns = new ArrayList<>();

        QueryParam params = new QueryParam();
        params.setNeedLimit(false);
        params.setRawSql(" SHOW COLUMNS IN \"" + tableName + "\"");
        DataVo dataVo = executeSql(ds, params);

        if (dataVo == null || dataVo.getRowSize() == 0) {
            return columns;
        }

        for (Map<String, Object> row : dataVo.getRows()) {
            String name = String.valueOf(row.get("column"));
            String type = String.valueOf(row.get("type")).toLowerCase();
            DataType dt = DataType.parse(type);
            ColumnVo vo = new ColumnVo();
            vo.setName(name);
            vo.setType(dt.getCode());
            vo.setOriginalType(type);
            columns.add(vo);
        }

        return columns;
    }


}
